/*
 * @Author: fanjs
 * @Date: 2025-03-03 15:24:06
 * @Description: 富文本编辑器
 */

import { useState, useEffect, forwardRef } from 'react'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor'
import { getServiceBaseURL } from '@/utils/service';
import { localStg } from '@/utils/storage';
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import './style.scss'

// 请求地址 + 代理
const isHttpProxy = import.meta.env.DEV && import.meta.env.VITE_SERVICE_BASE_URL;
const { baseURL } = getServiceBaseURL(import.meta.env as any, isHttpProxy);
const server = `${baseURL}/v1/upload/image`  // 上传图片的服务器地址

// 访问地址
const imageURL = import.meta.env.VITE_SERVICE_BASE_URL;

const MyEditor = forwardRef<any, { content: any, onChange: (value: any) => void }>(({ content, onChange }) => {
  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null)

  // 编辑器内容
  const [html, setHtml] = useState('')

  // 当内容变化时像父级传递值，节流控制 1s 执行一次
  useEffect(() => {
    const timer = setTimeout(() => onChange(html), 1000)
    return () => clearTimeout(timer)
  }, [html, onChange])

  useEffect(() => {
    setHtml(content)
  }, [content])

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {
    excludeKeys: [
      '|',
      'group-more-style',
      'fullScreen',
      'group-video',
      'insertVideo',
      'uploadVideo',
      'codeBlock',
      'insertTable'
    ]
  }

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: '请输入正文内容...',
    MENU_CONF: {
      uploadImage: {
        server,
        fieldName: 'file', // 上传图片的字段名
        maxFileSize: 5 * 1024 * 1024, // 限制图片大小 5M
        maxNumberOfFiles: 5, // 最多可上传 5 个文件
        allowedFileTypes: ['image/*'], // 允许上传的图片类型
        customInsert(res: any, insertFn: any) {
          const url = `${imageURL}${res.data.url}`;
          insertFn(url)
        },
        headers: {
          Authorization: `Bearer ${localStg.get('token')}`,
        },
        timeout: 10 * 1000, // 10 秒
      }
    }
  }

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return
      editor.destroy()
      setEditor(null)
    }
  }, [editor])

  return (
    <>
      <div className='z-100 rounded-large overflow-hidden border-2 border-default-100'>
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
        />
        <Editor
          defaultConfig={editorConfig}
          value={html}
          onCreated={setEditor}
          onChange={(editor) => setHtml(editor.getHtml())}
          className='h-[calc(100vh-304px)]'
        />
      </div>
    </>
  )
})

export default MyEditor
